package br.net.cep.util.db;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import wsl.controle.Controlador;
/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 * @author alexandre.araujo
 */
public class ConexaoDB {
    private static final SessionFactory sessionFactory = buildSessionFactory();    
    private static SessionFactory buildSessionFactory() {
        try {
            Configuration cfg = new Configuration();
            cfg.configure("/hibernate.cfg.xml");
            return cfg.buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            Controlador.getInstancia().addErro("erro no init:"+ex.getMessage().toString());
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }    
    public static void salvar(Object objetoInstance){
	        try { 
	            ConexaoDB.getSessionFactory().getCurrentSession().saveOrUpdate(objetoInstance); 
	        }catch (Exception e) {
	            Controlador.getInstancia().addErro( "erro ao salvar no db: "+e.getMessage().toString());
	        }
	    }
      public static boolean deletar(Object objetoInstance){
        boolean concluido = false;
        try{            
           ConexaoDB.getSessionFactory().getCurrentSession().delete(objetoInstance);
           concluido=true;
        } catch (Exception e) {
            Controlador.getInstancia().addErro("erro ao deletar no db: "+e.getMessage().toString());    	
        }
        return concluido;
     }
    public static List<?> listar(String sql){
        List<?> listP = null;
        try {
            listP = ConexaoDB.getSessionFactory().getCurrentSession().createQuery(sql).list();
        } catch (Exception e) {
            Controlador.getInstancia().addErro("erro ao listar no db: "+e.getMessage().toString());
        }
        return listP;
    }    
    public static void fecharSesssao(){           
        ConexaoDB.getSessionFactory().getCurrentSession().getTransaction().commit();
    }
    public static void iniciarSessao(){
        ConexaoDB.getSessionFactory().getCurrentSession().beginTransaction();
    }    
}